<template>
  <div class="products-container">
    <el-card class="products-card">
      <div class="header-section">
        <h2>Product Management</h2>
        <el-button type="primary" @click="showAddProductDialog">Add Product</el-button>
      </div>
      
      <!-- Search and Filter -->
      <div class="filter-section">
        <el-input 
          v-model="searchQuery" 
          placeholder="Search products..." 
          prefix-icon="Search"
          style="max-width: 300px; margin-right: 15px;"
        />
        <el-select v-model="filterStatus" placeholder="Filter by status" style="max-width: 200px;">
          <el-option label="All" value=""></el-option>
          <el-option label="Active" value="ACTIVE"></el-option>
          <el-option label="Inactive" value="INACTIVE"></el-option>
        </el-select>
      </div>
      
      <!-- Products Table -->
      <el-table 
        :data="filteredProducts" 
        style="width: 100%; margin-top: 20px;" 
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="Name" width="200"></el-table-column>
        <el-table-column prop="description" label="Description"></el-table-column>
        <el-table-column prop="price" label="Price" width="120">
          <template #default="scope">
            ${{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'info'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template #default="scope">
            <el-button size="small" @click="editProduct(scope.row)">Edit</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'ACTIVE' ? 'info' : 'success'"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 'ACTIVE' ? 'Deactivate' : 'Activate' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteProduct(scope.row)">Delete</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredProducts.length"
        />
      </div>
    </el-card>
    
    <!-- Add/Edit Product Dialog -->
    <el-dialog 
      :title="editingProduct ? 'Edit Product' : 'Add Product'" 
      v-model="dialogVisible" 
      width="500px"
    >
      <el-form :model="productForm" :rules="productRules" ref="productFormRef" label-width="100px">
        <el-form-item label="Name" prop="name">
          <el-input v-model="productForm.name" placeholder="Enter product name"></el-input>
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="Enter product description"
          ></el-input>
        </el-form-item>
        <el-form-item label="Price" prop="price">
          <el-input v-model="productForm.price" placeholder="Enter product price"></el-input>
        </el-form-item>
        <el-form-item label="Status" prop="status">
          <el-switch
            v-model="productForm.status"
            :active-value="'ACTIVE'"
            :inactive-value="'INACTIVE'"
            active-text="Active"
            inactive-text="Inactive"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="saveProduct">Save</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed } from 'vue'

export default {
  name: 'MerchantProducts',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const editingProduct = ref(null)
    
    const searchQuery = ref('')
    const filterStatus = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    const products = ref([
      {
        id: 1,
        name: 'Sample Product 1',
        description: 'This is a sample product description',
        price: '19.99',
        status: 'ACTIVE'
      },
      {
        id: 2,
        name: 'Sample Product 2',
        description: 'This is another sample product',
        price: '29.99',
        status: 'ACTIVE'
      },
      {
        id: 3,
        name: 'Inactive Product',
        description: 'This product is currently inactive',
        price: '39.99',
        status: 'INACTIVE'
      }
    ])
    
    const productForm = reactive({
      name: '',
      description: '',
      price: '',
      status: 'ACTIVE'
    })
    
    const productRules = {
      name: [
        { required: true, message: 'Please enter product name', trigger: 'blur' }
      ],
      description: [
        { required: true, message: 'Please enter product description', trigger: 'blur' }
      ],
      price: [
        { required: true, message: 'Please enter product price', trigger: 'blur' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: 'Please enter a valid price', trigger: 'blur' }
      ]
    }
    
    const filteredProducts = computed(() => {
      let result = products.value
      
      // Apply search filter
      if (searchQuery.value) {
        result = result.filter(product => 
          product.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          product.description.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      // Apply status filter
      if (filterStatus.value) {
        result = result.filter(product => product.status === filterStatus.value)
      }
      
      // Apply pagination
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return result.slice(start, end)
    })
    
    const showAddProductDialog = () => {
      editingProduct.value = null
      Object.assign(productForm, {
        name: '',
        description: '',
        price: '',
        status: 'ACTIVE'
      })
      dialogVisible.value = true
    }
    
    const editProduct = (product) => {
      editingProduct.value = product
      Object.assign(productForm, product)
      dialogVisible.value = true
    }
    
    const saveProduct = async () => {
      // In a real application, you would make an API call to save the product
      // For now, using a mock implementation
      try {
        loading.value = true
        
        if (editingProduct.value) {
          // Update existing product
          Object.assign(editingProduct.value, productForm)
          ElMessage.success('Product updated successfully!')
        } else {
          // Add new product
          const newProduct = {
            id: products.value.length + 1,
            ...productForm
          }
          products.value.push(newProduct)
          ElMessage.success('Product added successfully!')
        }
        
        dialogVisible.value = false
      } catch (error) {
        console.error('Save product error:', error)
        ElMessage.error('An error occurred while saving the product')
      } finally {
        loading.value = false
      }
    }
    
    const toggleStatus = (product) => {
      product.status = product.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
      const action = product.status === 'ACTIVE' ? 'activated' : 'deactivated'
      ElMessage.success(`Product ${action} successfully!`)
    }
    
    const deleteProduct = (product) => {
      ElMessageBox.confirm(
        `Are you sure you want to delete the product "${product.name}"?`,
        'Confirm Delete',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      ).then(() => {
        const index = products.value.findIndex(p => p.id === product.id)
        if (index !== -1) {
          products.value.splice(index, 1)
          ElMessage.success('Product deleted successfully!')
        }
      }).catch(() => {
        // User cancelled
      })
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    return {
      loading,
      dialogVisible,
      editingProduct,
      searchQuery,
      filterStatus,
      currentPage,
      pageSize,
      products,
      productForm,
      productRules,
      filteredProducts,
      showAddProductDialog,
      editProduct,
      saveProduct,
      toggleStatus,
      deleteProduct,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.products-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.products-card {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  text-align: center;
}
</style>